<?php

class NetworkController extends BaseController {
        
    public function indexAction($request) {
    	if(!$this->check_user_session($request)) return;
    }
    
    public function inviteAction($request) {
    	if(isset($request['invite'])) {
    		$token = base64_decode($request['token']);
    		if(file_exists($token)) {
    			$cacheData = file_get_contents($token);
    			$this->data['emails'] = unserialize($cacheData);
    			$this->data['token'] = $request['token'];
    		}
    		if(!isset($request['emails'])) {
    			$this->data['error'] = "Please choose contact/s to invite.";
    		} else {
    			#TODO: send email here
    		}
    		return;
    	}
    	if(isset($request['gmail'])) {
    		$cache = sprintf("cache/emails_%s.txt", md5($request['Email'].$request['Passwd'].date("mdY")));
    		$this->data['token'] = base64_encode($cache);
    		if(file_exists($cache)) {
    			$cacheData = file_get_contents($cache);
    			$this->data['emails'] = unserialize($cacheData);
    			return;
    		}
	    	$loginUrl = "https://www.google.com/accounts/ClientLogin";
	    	$params = sprintf("accountType=GOOGLE&Email=%s&Passwd=%s&service=cp&source=peak-network-1", urlencode($request['Email']), urlencode($request['Passwd']));
	    	$headers = array();
	    	$headers[] = 'Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2';
			$headers[] = 'Connection: Keep-Alive';
			$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; 
	    	$ch = curl_init($loginUrl);
	    	curl_setopt ($ch, CURLOPT_POST, TRUE);
	        curl_setopt ($ch, CURLOPT_HEADER, FALSE);
	        curl_setopt ($ch, CURLOPT_USERAGENT, "ASO");
	        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
	        curl_setopt ($ch, CURLOPT_REFERER, "");
	        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	        curl_setopt ($ch, CURLOPT_MAXREDIRS, 5);
	        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
	        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
	    	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	    	$result = curl_exec($ch);
	    	preg_match('/Auth=(.*)/', $result, $auth);
	    	if(isset($auth[1])) {
	    		$feedUrl = sprintf("http://www.google.com/m8/feeds/contacts/%s/full", urlencode($request['Email']));
	    		$headers = array();
	    		$headers[] = 'Content-Type: application/x-www-form-urlencoded';
				$headers[] = sprintf('Authorization: GoogleLogin auth="%s"', $auth[1]);
				$headers[] = 'User-Agent: Java/1.5.0_06';
				$headers[] = 'Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2';
				$headers[] = 'Connection: keep-alive';
				$ch = curl_init($feedUrl);
				curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
	        	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
	        	curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, TRUE);
		        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
		        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
				$result = curl_exec($ch);
				require APP_PATH. "lib/XML2array.php";
				$xml = xml2array($result);
				$emails = array();
				if(isset($xml['feed']['entry'])) {
					foreach($xml['feed']['entry'] as $entry) {
						$name = isset($entry['title']['value']) ? $entry['title']['value'] : "";
						$email = isset($entry['gd:email']['attr']['address']) ? $entry['gd:email']['attr']['address'] : "";
						$emails[] = array('name'=>$name, 'email'=>$email);
					}
					$this->data['emails'] = $emails;
					$fh = fopen($cache, "w");
					if($fh) {
						fwrite($fh, serialize($emails));
						fclose($fh);
					}
				} else {
					$this->data['error'] = "Authentication failed.";
				}
	    	} else {
				$this->data['error'] = "Authentication failed.";
			}
    	}
    }
    
    public function profileAction($request) {
    	
    }
    
    public function browseAction($request) {
    	$this->data['profiles'] = pk_profile::getAll(array(), array(), 10);
    	$count = 0;
    	foreach($this->data['profiles'] as $profile) {
    		$this->data['profiles'][$count]->user = pk_user::get($profile->user);
    		$count++;
    	}
    }
    
    public function members_areaAction($request) {
    	if(pk_user::isLoggedIn()) {
    		BaseController::forward('Network', 'index');
    		NetworkController::indexAction($request);
    		return;
    	}
    	if(isset($request['login'])) {
    		$user = pk_user::get($request['username'], 'username');
    		if($user->id > 0 && $user->verified && $user->enabled) {
    			if($user->password == crypt($request['password'], sprintf("$1$%s$", substr($user->salt, 0, 8)))) {
    				$_SESSION['pk_user'] = $user->id;    			
	    			if(isset($request['remember'])) {
	    				setcookie("pk_user", sprintf('%u', crc32($user->id)), time()+3*24*60*60, "/", str_replace('www', '', $_SERVER['HTTP_HOST']));
	    			}
    				BaseController::redirect("../network/");
    			} else {
    				$this->data['error'] = "Wrong ID and/or password";
    			}
    		} else {
    			$this->data['error'] = "Wrong ID and/or password";
    		}
    	}
    	
    	if(isset($request['register'])) {
    		$user = new pk_user($request);
    		$profile = new pk_profile($request);
    		
    		$errors = array();
    		if(trim($profile->name) == "") {
    			$errors[] = "Name";
    		}
    		if(trim($user->username) == "") {
    			$errors[] = "Member ID";
    		} else {    		
    			$test = pk_user::get($request['username'], 'username');
    			if($test->id > 0) {
    				$errors[] = "Member ID is not available";
    			}
    		}
    		if(trim($user->password) == "") {
    			$errors[] = "Password";
    		} else {
    			if(!isset($user->password[5])) {
    				$errors[] = "Password must be at least 6 characters";
    			} else if(trim($request['password2']) == "") {
	    			$errors[] = "Confirm Password";
	    		} else {
	    			if($user->password != $request['password2']) {
	    				$errors[] = "Password does not match";
	    			}
	    		}
    		}
    		if(trim($user->email) == "") {
    			$errors[] = "Email address";
    		} else {
    			$test = pk_user::get($request['email'], 'email');
    			if($test->id > 0) {
    				$errors[] = "Email address already in use";
    			}
    		}
    		if(!empty($errors)) {
    			$this->data['errors'] = $errors;
    		} else {
    			$hash = md5(rand(1, 100));
    			$user->salt = substr($hash, 0, 8);
    			$user->password = crypt($user->password, sprintf("$1$%s$", $user->salt));
    			$user->save();
    			$profile->user = $user->id;
    			$profile->save();
    			if(isset($request['remember'])) {
    				setcookie("pk_user", sprintf('%u', crc32($user->id)), time()+3*24*60*60, "/", str_replace('www', '', $_SERVER['HTTP_HOST']));
    			}
    			$_SESSION['pk_user'] = $user->id;
    			BaseController::redirect("../network/");
    			#TODO: send email here
    		}
    	}
    }
    
    public function logoutAction($request) {
    	if(isset($_COOKIE['pk_user'])) {
    		setcookie("pk_user", "0", time()-1, "/", str_replace('www', '', $_SERVER['HTTP_HOST']));
    	}
    	if(isset($_SESSION['pk_user'])) {
    		unset($_SESSION['pk_user']);
    	}
    	BaseController::forward('Network', 'members_area');
    	NetworkController::members_areaAction($request);
    }
    
    /**
     * 
     * @param $request
     * @return boolean
     */    
    private function check_user_session($request) {
		if(!pk_user::isLoggedIn()) {
    		BaseController::forward('Network', 'members_area');
    		NetworkController::members_areaAction($request);
			return false;
		}
		return true;
    }

}

?>